package com.fuluwa.domain.bank.service;

import com.fuluwa.domain.bank.dto.AccountDTO;
import com.fuluwa.domain.bank.model.Account;
import com.fuluwa.domain.bank.model.EarningDefine;
import com.fuluwa.domain.bank.repository.AccountRepository;
import com.fuluwa.domain.security.model.User;
import com.fuluwa.infra.event.GlobalEvent;
import com.fuluwa.infra.event.GlobalEvent.EventType;
import com.fuluwa.infra.exception.PersistenceException;
import java.io.PrintStream;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

@Component
public class BankEventListener
  implements ApplicationListener<GlobalEvent>
{

  @Autowired
  AccountService accountService;

  @Autowired
  AccountRepository accountRepository;

  public void onApplicationEvent(GlobalEvent event)
  {
    System.out.println("New Event!");
    if (event.getType().equals(GlobalEvent.EventType.REGISTED)) {
      User u = (User)event.getSource();
      List<Account> accounts = this.accountRepository.findByUser(u);
      Account silverAccount = null;
      for (Account account : accounts) {
        if (account.isSilverAccount()) {
          silverAccount = account;
          break;
        }
      }
      AccountDTO dto = new AccountDTO();
      dto.setAccountNo(silverAccount.getAccountNo());

      EarningDefine earnDef = EarningDefineHelper.getInstance().find(event.getType(), silverAccount.getAccountType());

      dto.setAmount(earnDef.getAmount());
      dto.setReferenceNo("11122200");
      dto.setTxtTxnDesc("Register successful");
      try {
        this.accountService.deposit(dto);
      }
      catch (PersistenceException e) {
        e.printStackTrace();
      }
    }
  }
}